# -*- coding: utf-8 -*-
"""
生成压力测试简洁报告

从详细CSV生成一个简洁的汇总报告CSV
"""
import sys
import pandas as pd
from pathlib import Path
from datetime import datetime

def generate_report(detail_csv_path):
    """生成简洁报告"""
    print("=" * 60)
    print("生成压力测试报告")
    print("=" * 60)
    
    # 读取详细结果
    df = pd.read_csv(detail_csv_path)
    
    print(f"\n📊 读取文件: {detail_csv_path}")
    print(f"📝 总测试数: {len(df)}")
    
    # 计算统计数据
    total_tests = len(df)
    successful_tests = df['success'].sum()
    understood_tests = df['understood'].sum()
    
    # 响应时间统计
    avg_time = df['elapsed_time'].mean()
    median_time = df['elapsed_time'].median()
    min_time = df['elapsed_time'].min()
    max_time = df['elapsed_time'].max()
    std_time = df['elapsed_time'].std()
    
    # 按线程统计
    thread_stats = []
    for thread_id in sorted(df['thread_id'].unique()):
        thread_df = df[df['thread_id'] == thread_id]
        thread_stats.append({
            '线程ID': thread_id,
            '测试数': len(thread_df),
            '成功数': thread_df['success'].sum(),
            '成功率(%)': thread_df['success'].sum() / len(thread_df) * 100,
            '平均响应(秒)': thread_df['elapsed_time'].mean(),
            '最快响应(秒)': thread_df['elapsed_time'].min(),
            '最慢响应(秒)': thread_df['elapsed_time'].max()
        })
    
    # 响应时间分布
    bins = [0, 1, 2, 3, 5, 10, float('inf')]
    labels = ['<1s', '1-2s', '2-3s', '3-5s', '5-10s', '>10s']
    df['time_range'] = pd.cut(df['elapsed_time'], bins=bins, labels=labels)
    time_dist = df['time_range'].value_counts().sort_index()
    
    time_dist_data = []
    for label in labels:
        count = time_dist.get(label, 0)
        percentage = count / len(df) * 100
        time_dist_data.append({
            '响应时间范围': label,
            '数量': count,
            '占比(%)': percentage
        })
    
    # 创建报告
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    report_path = Path(detail_csv_path).parent / f"stress_test_report_{timestamp}.csv"
    
    # 写入报告
    with open(report_path, 'w', encoding='utf-8-sig') as f:
        # 总体统计
        f.write("压力测试报告\n")
        f.write(f"生成时间,{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
        f.write(f"数据来源,{detail_csv_path.name}\n")
        f.write("\n")
        
        f.write("总体统计\n")
        f.write("指标,数值\n")
        f.write(f"总测试数,{total_tests}\n")
        f.write(f"成功数,{successful_tests}\n")
        f.write(f"成功率(%),{successful_tests/total_tests*100:.1f}\n")
        f.write(f"理解数,{understood_tests}\n")
        f.write(f"理解率(%),{understood_tests/total_tests*100:.1f}\n")
        f.write("\n")
        
        f.write("响应时间统计\n")
        f.write("指标,数值(秒)\n")
        f.write(f"平均响应,{avg_time:.2f}\n")
        f.write(f"中位数响应,{median_time:.2f}\n")
        f.write(f"最快响应,{min_time:.2f}\n")
        f.write(f"最慢响应,{max_time:.2f}\n")
        f.write(f"标准差,{std_time:.2f}\n")
        f.write("\n")
        
        # 按线程统计
        f.write("按线程统计\n")
        df_thread = pd.DataFrame(thread_stats)
        df_thread.to_csv(f, index=False, lineterminator='\n')
        f.write("\n")
        
        # 响应时间分布
        f.write("响应时间分布\n")
        df_time_dist = pd.DataFrame(time_dist_data)
        df_time_dist.to_csv(f, index=False, lineterminator='\n')
    
    print(f"\n✅ 报告已生成: {report_path}")
    
    # 显示摘要
    print("\n" + "=" * 60)
    print("报告摘要")
    print("=" * 60)
    print(f"\n📊 总体:")
    print(f"  测试数: {total_tests}")
    print(f"  成功率: {successful_tests/total_tests*100:.1f}%")
    print(f"  理解率: {understood_tests/total_tests*100:.1f}%")
    
    print(f"\n⏱️  响应时间:")
    print(f"  平均: {avg_time:.2f}秒")
    print(f"  中位数: {median_time:.2f}秒")
    print(f"  范围: {min_time:.2f}s - {max_time:.2f}s")
    
    print(f"\n🧵 线程性能:")
    for stat in thread_stats:
        print(f"  线程{stat['线程ID']}: {stat['成功率(%)']:.0f}% 成功, 平均 {stat['平均响应(秒)']:.2f}s")
    
    print(f"\n📈 响应时间分布:")
    for item in time_dist_data:
        if item['数量'] > 0:
            bar = '█' * int(item['占比(%)'] / 2)
            print(f"  {item['响应时间范围']:6s}: {item['数量']:3d} ({item['占比(%)']:5.1f}%) {bar}")
    
    print("\n" + "=" * 60)
    
    return report_path


def main():
    if len(sys.argv) < 2:
        # 查找最新的压力测试结果文件
        storage_path = Path("storage")
        csv_files = list(storage_path.glob("stress_test_detail_*.csv"))
        
        if not csv_files:
            print("❌ 未找到压力测试结果文件")
            print("使用方法: python generate_stress_report.py <csv文件路径>")
            return
        
        # 使用最新的文件
        csv_path = max(csv_files, key=lambda p: p.stat().st_mtime)
        print(f"📂 使用最新的测试结果: {csv_path}\n")
    else:
        csv_path = Path(sys.argv[1])
        
        if not csv_path.exists():
            print(f"❌ 文件不存在: {csv_path}")
            return
    
    generate_report(csv_path)


if __name__ == "__main__":
    main()
